#include "udp.h"

Udp::Udp()
{
    sockfd=socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) perror("Opening socket");
}

void Udp::enviar(char buffer[]){
    n=sendto(sockfd,buffer, strlen(buffer),0,(const struct sockaddr *)&pc2,length);
      if (n < 0) perror("Sendto");
}
void Udp::enviar (char buffer[],int puerto, char *host){
    pc2.sin_family = AF_INET;
    hp = gethostbyname(host);
    if (hp==0) perror("Unknown host");

    bcopy((char *)hp->h_addr,
         (char *)&pc2.sin_addr,
          hp->h_length);
    pc2.sin_port = htons(puerto);
    length=sizeof(struct sockaddr_in);
    n=sendto(sockfd, buffer, strlen(buffer),0,(const struct sockaddr *)&pc2,length);
      if (n < 0) perror("Sendto");
}
char* Udp::recibir(int puerto){
       bzero(buffer,2048);
       length = sizeof(server);
       bzero(&server,length);
       server.sin_family=AF_INET;
       server.sin_addr.s_addr=INADDR_ANY;
       server.sin_port=htons(puerto);
       if (bind(sockfd,(struct sockaddr *)&server,length)<0)
           perror("binding");
       fromlen = sizeof(struct sockaddr_in);
        n = recvfrom(sockfd,buffer,1024,0,(struct sockaddr *)&pc2,&fromlen);
        if (n < 0) perror("recvfrom");
        char *buff=buffer;
        return buff;
}
char* Udp::recibir(){
    bzero(buffer,2048);
    n = recvfrom(sockfd,buffer,1024,0,(struct sockaddr *)&pc2,&fromlen);
    if (n < 0) perror("recvfrom");
    char *buff=buffer;
    return buff;
}

void Udp::conexion(int puerto, char *host){
    pc2.sin_family = AF_INET;
    hp = gethostbyname(host);
    if (hp==0) perror("Unknown host");

    bcopy((char *)hp->h_addr,
         (char *)&pc2.sin_addr,
          hp->h_length);
    pc2.sin_port = htons(puerto);
    length=sizeof(struct sockaddr_in);

}
